class Variant < ActiveRecord::Base
  set_table_name :product_variants

  belongs_to :product

  has_many :order_items

  has_many :photos, :as => :viewable, :order => :position, :dependent => :destroy
  has_and_belongs_to_many :parameter_values, :join_table => "variant_has_parameter_values"
  has_and_belongs_to_many :parameters, :join_table => "product_parameter_values"
  
  validates :price, :number, :state, :presence => true
  validates :price, :numericality => {:greater_than => 0}
  validates :number, :uniqueness => true, :length => {:maximum => 30}, :format => {:with => Format::STRING_REGEX}
  validates :parameter_values, :presence => true, :unless => Proc.new {|variant| variant.is_master?}

  def is_master?
    !!is_master
  end

  def parameter_values_to_sentence
    parameter_values.blank? ? "Nemá žádné parametry" : parameter_values.map(&:value).to_sentence
  end
end